package cn.cds.withyou.admin.ui.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.IntDef;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.cds.withyou.admin.R;

/**
 * <p> Description:</p>
 * <p/>
 * <p>Copyright: Copyright (c) 2015
 *
 * @author json01.li
 * @Version 1.0
 * @CreateTime 2015/10/30 15:19
 **/
public class CommonTitleBar extends RelativeLayout {

    /**
     * Common Title Bar 左侧按钮id
     */
    public static final int LEFT_BUTTON_ID = R.id.common_title_left_img;

    /**
     * Common Title Bar 右侧按钮id
     */
    public static final int RIGHT_BUTTON_ID = R.id.common_title_right_img;

    @IntDef(value = {LEFT_BUTTON, RIGHT_BUTTON}, flag = true)
    @Retention(RetentionPolicy.SOURCE)
    public @interface TopButton {
    }

    public final static int LEFT_BUTTON = 0x01;

    public final static int RIGHT_BUTTON = 0x02;

    @Bind(R.id.common_title_tv)
    TextView mTitleTv;
    @Bind(R.id.common_title_left_img)
    ImageView mLeftImg;
    @Bind(R.id.common_title_right_img)
    ImageView mRightImg;

    public CommonTitleBar(Context context) {
        this(context, null, 0);
    }

    public CommonTitleBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0, 0);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public CommonTitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr, 0);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CommonTitleBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs, defStyleAttr, defStyleRes);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable
                .CommonTitleBarAttr, defStyleAttr, defStyleRes);
        String title = typedArray.getString(R.styleable.CommonTitleBarAttr_titleStr);
        Drawable leftDrawable = typedArray.getDrawable(R.styleable.CommonTitleBarAttr_leftDrawable);
        Drawable rightDrawable = typedArray.getDrawable(R.styleable
                .CommonTitleBarAttr_rightDrawable);
        Drawable titleDrawable = typedArray.getDrawable(R.styleable.CommonTitleBarAttr_titleBackground);
        int titleColor = typedArray.getColor(R.styleable.CommonTitleBarAttr_titleColor, Color.TRANSPARENT);
        String onLeftClick = typedArray.getString(R.styleable.CommonTitleBarAttr_onLeftClick);
        String onRightClick = typedArray.getString(R.styleable.CommonTitleBarAttr_onRightClick);
        typedArray.recycle();

        inflate(this.getContext(), R.layout.common_title_bar, this);
        ButterKnife.bind(this, this);

        if (!TextUtils.isEmpty(title)) {
            mTitleTv.setText(title);
        }
        if (null != leftDrawable) {
            mLeftImg.setImageDrawable(leftDrawable);
            mLeftImg.setVisibility(View.VISIBLE);
        }
        if (null != rightDrawable) {
            mRightImg.setImageDrawable(rightDrawable);
            mRightImg.setVisibility(View.VISIBLE);
        }
        if(null != titleDrawable) {
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mTitleTv.setBackground(titleDrawable);
            } else {
                //noinspection deprecation
                mTitleTv.setBackgroundDrawable(titleDrawable);
            }
        }
        if (Color.TRANSPARENT != titleColor) {
            mTitleTv.setTextColor(titleColor);
        }
        handleClickListener(mLeftImg, onLeftClick);
        handleClickListener(mRightImg, onRightClick);

        if (null == getBackground()) {
            setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimary));
        }
    }

    private void handleClickListener(View v, final String onClick) {
        if (TextUtils.isEmpty(onClick)) {
            return;
        }
        v.setOnClickListener(new OnClickListener() {

            private Method mHandleMethod;

            @Override
            public void onClick(View v) {
                if (null == mHandleMethod) {
                    try {
                        mHandleMethod = v.getContext().getClass().getMethod(onClick, View.class);
                    } catch (NoSuchMethodException e) {
                        int id = getId();
                        String idText = id == NO_ID ? "" : " with id '"
                                + getContext().getResources().getResourceEntryName(
                                id) + "'";
                        throw new IllegalStateException("Could not find a method " +
                                onClick + "(View) in the activity "
                                + getContext().getClass() + " for onLeftClick/onRightClick handler"
                                + " on view " + CommonTitleBar.this.getClass() + idText, e);
                    }
                }
                try {
                    mHandleMethod.invoke(v.getContext(), v);
                } catch (InvocationTargetException e) {
                    throw new IllegalStateException("Could not execute non "
                            + "public method of the activity", e);
                } catch (IllegalAccessException e) {
                    throw new IllegalStateException("Could not execute "
                            + "method of the activity", e);
                }
            }
        });
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        mTitleTv.setText(title);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(int title) {
        setTitle(getResources().getString(title));
    }

    /**
     * 设置顶部栏按钮类型，{@link #LEFT_BUTTON} 为左边按钮，{@link #RIGHT_BUTTON}为右边按钮，同时设置传递 {@link
     * #LEFT_BUTTON} | {@link #RIGHT_BUTTON}
     *
     * @param type
     */
    public void setButtonType(@TopButton int type) {
        if ((type & LEFT_BUTTON) > 0) {
            mLeftImg.setVisibility(View.VISIBLE);
        } else {
            mLeftImg.setVisibility(View.GONE);
        }
        if ((type & RIGHT_BUTTON) > 0) {
            mRightImg.setVisibility(View.VISIBLE);
        } else {
            mRightImg.setVisibility(View.GONE);
        }
    }

    /**
     * 设置顶部栏icon
     *
     * @param type       {@link #LEFT_BUTTON} for left button and {@link #RIGHT_BUTTON} for right
     *                                       button
     * @param drawableId icon id，drawableId <= 0则隐藏
     */
    public void setButtonIcon(@TopButton int type, int drawableId) {
        setButtonIcon(type, drawableId > 0 ? getResources().getDrawable(drawableId) : null);
    }

    /**
     * 设置顶部栏icon
     *
     * @param type     {@link #LEFT_BUTTON} for left button and {@link #RIGHT_BUTTON} for right
     *                                     button
     * @param drawable icon， null == drawable 则隐藏
     */
    public void setButtonIcon(@TopButton int type, Drawable drawable) {
        if ((type & LEFT_BUTTON) > 0) {
            if (null != drawable) {
                mLeftImg.setImageDrawable(drawable);
                mLeftImg.setVisibility(View.VISIBLE);
            } else {
                mLeftImg.setVisibility(View.GONE);
            }
        }
        if ((type & RIGHT_BUTTON) > 0) {
            if (null != drawable) {
                mRightImg.setImageDrawable(drawable);
                mRightImg.setVisibility(View.VISIBLE);
            } else {
                mRightImg.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 设置顶部栏按钮点击事件
     *
     * @param type     {@link #LEFT_BUTTON} for left button and {@link #RIGHT_BUTTON} for right
     *                                     button
     * @param listener 点击事件
     */
    public void setButtonOnClickListener(@TopButton int type, OnClickListener listener) {
        if ((type & LEFT_BUTTON) > 0) {
            mLeftImg.setOnClickListener(listener);
        }
        if ((type & RIGHT_BUTTON) > 0) {
            mRightImg.setOnClickListener(listener);
        }
    }

    /**
     * 获取顶部栏按钮类型
     *
     * @return {@link #LEFT_BUTTON} 为左按钮，{@link #RIGHT_BUTTON}为右按钮，{@link #LEFT_BUTTON}|{@link
     * #RIGHT_BUTTON} 为左右按钮
     */
    public int getButtonType() {
        int type = 0x0;
        if (View.VISIBLE == mLeftImg.getVisibility()) {
            type |= LEFT_BUTTON;
        }
        if (View.VISIBLE == mRightImg.getVisibility()) {
            type |= RIGHT_BUTTON;
        }
        return type;
    }
}
